#include "QExploreBotStats.h"
#include "ExplorBotLibrary.h"
#include "ExplorBot.h"
#include "ExplorBotDialog.h"
#include <QLabel>
#include <QPushButton>
#include <QIcon>
#include <QPixmap>

QExploreBotStats* QExploreBotStats::instance = NULL;

QExploreBotStats* QExploreBotStats::getInstance(){
	if( instance == NULL ){
		instance = new QExploreBotStats(NULL);
	}
	return instance;
}

QExploreBotStats::QExploreBotStats(QWidget *parent)
	: QWidget(parent){
	ui.setupUi(this);
}

QExploreBotStats::~QExploreBotStats(){

}

void QExploreBotStats::init(){
	_signalMapper = new QSignalMapper(this);
	connect(_signalMapper, SIGNAL(mapped(int)), this, SLOT(showExploreBotDialog(int)));
	_ebList = ExplorBotLibrary::getInstance()->getAutoApplyExplorBot();
	for (int i=0;i<_ebList.size();i++)
	{
		QLabel* icb;
		if (_ebList.at(i)->getStats())
		{
			icb = new QLabel("<img src=\"images/green_light.png\" width=\"20\" height=\"20\">"
				+QString::fromStdString(_ebList.at(i)->getMessage()));
		} 
		else
		{
			icb = new QLabel("<img src=\"images/red_light.png\" width=\"20\" height=\"20\">"
				+QString::fromStdString(_ebList.at(i)->getMessage()));
		}
		ui.gridLayout->addWidget(icb,i%5,(i/5)*2);
		QPushButton* namelabel = new QPushButton(QString::fromStdString(_ebList.at(i)->getName()));
		namelabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
		_ebpbList.push_back(namelabel);
		ui.gridLayout->addWidget(namelabel,i%5,((i/5)*2+1));
		_signalMapper->setMapping(namelabel, i);
		connect(namelabel, SIGNAL(clicked()), _signalMapper, SLOT(map()));
	}
}

void QExploreBotStats::update(){
	clear();
	init();
}

void QExploreBotStats::clear(){
	QLayoutItem* item;
	_ebList.clear();
	while ( ( item = ui.gridLayout->takeAt( 0 ) ) != NULL )
	{
		delete item->widget();
		delete item;
	}
}

void QExploreBotStats::showExploreBotDialog(int i){
	_ebList.at(i)->getDialog()->show();
	ExplorBotLibrary::getInstance()->removeExplorBot(_ebList.at(i));
}